package com.oig.sys.msg.im.handler.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Throwables;
import com.oig.common.constants.CommonConstants;
import com.oig.common.util.JsonUtil;
import com.oig.sys.msg.constants.MsgEnums;
import com.oig.sys.msg.im.handler.BaseHandler;
import com.oig.sys.msg.vo.NoticeMsgVo;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.error.WxMpErrorMsgEnum;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.api.impl.WxCpMessageServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpUserServiceImpl;
import me.chanjar.weixin.cp.bean.message.WxCpMessage;
import me.chanjar.weixin.cp.bean.message.WxCpMessageSendResult;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class EnterpriseWeChatHandler extends BaseHandler {

    public EnterpriseWeChatHandler() {
        channelCode = MsgEnums.MsgChannel.ENTERPRISE_WE_CHAT.getCode() + MsgEnums.MsgChannel.ENTERPRISE_WE_CHAT.getNoticeTypeCode();
    }

    @Override
    public boolean handler(NoticeMsgVo noticeMsg) {
        try {
            WxCpDefaultConfigImpl accountConfig = JsonUtil.toObject(noticeMsg.getChannelConfig(), WxCpDefaultConfigImpl.class);
            WxCpMessageServiceImpl messageService = new WxCpMessageServiceImpl(initService(accountConfig));
            List<String> userIdList = getUserIdList(accountConfig, noticeMsg.getMobiles());
            WxCpMessageSendResult result = messageService.send(buildWxCpMessage(noticeMsg, accountConfig.getAgentId(), userIdList));
            if (Integer.valueOf(WxMpErrorMsgEnum.CODE_0.getCode()).equals(result.getErrCode())) {
                return true;
            }
            log.error("EnterpriseWeChatHandler#handler fail!result:{},params:{}", JSON.toJSONString(result), JSON.toJSONString(noticeMsg));
        } catch (Exception e) {
            log.error("EnterpriseWeChatHandler#handler fail:{},params:{}",
                    Throwables.getStackTraceAsString(e), JSON.toJSONString(noticeMsg));
        }
        return false;
    }

    private List<String> getUserIdList(WxCpDefaultConfigImpl accountConfig, List<String> mobiles) throws WxErrorException {
        List<String> userIdList = new ArrayList<>();
        WxCpUserServiceImpl wxCpUserService = new WxCpUserServiceImpl(initService(accountConfig));
        for (String mobile : mobiles) {
            String userId = wxCpUserService.getUserId(mobile);
            userIdList.add(userId);
        }
        return userIdList;
    }


    /**
     * 初始化 WxCpServiceImpl 服务接口
     *
     */
    private WxCpService initService(WxCpDefaultConfigImpl config) {
        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);
        return wxCpService;
    }

    /**
     * 构建企业微信下发消息的对象
     * @param agentId   应用ID
     */
    private WxCpMessage buildWxCpMessage(NoticeMsgVo noticeMsg, Integer agentId, List<String> receiver) {
        String userId = StringUtils.join(receiver, CommonConstants.RADICAL);
        WxCpMessage wxCpMessage = WxCpMessage.TEXT().content(noticeMsg.getContent()).build();
        wxCpMessage.setAgentId(agentId);
        wxCpMessage.setToUser(userId);
        return wxCpMessage;
    }


}
